<template>
	<view class="bef7 h100vh pt90">
		<u-button class="w50 bs16" type="success" icon="weixin-circle-fill" text="微信登录" @click="handleLogin"></u-button>
	</view>
</template>

<script>
	const $index = require('../../request/api/v1/index');
	export default {
		data() {
			return {
				appID: "wx436121832ee5741d",
				appSecret: "054d762caffa76ba578382f632a42a1b",
				isLoggedIn: false,
				userInfo: {},
				userid: ''
			};
		},
		onLoad() {},
		async mounted() {
			this.getUserOpenid();
			console.log("组件挂载中...");
			// if (await this.isIngCompare()) {
			// 	console.log("正在比较...");
			// 	this.getMessagesList();
			// 	this.getwxCode();
			// 	this.handleTabUrl();
			// } else {
			// 	console.log("没有进行比较，调用getMessagesList...");
			// 	this.getMessagesList();
			// 	this.handleTabUrl();
			// }
			this.getwxCode();
		},
		methods: {
			async handleLogin() {
				console.log("进入handleLogin函数");
				// uni.setStorageSync("wechat_login_tag", "true");
				const appID = this.appID;
				const appSecret = this.appSecret;
				// this.isLoggedIn = true
				let currentUrl = window.location.href;
				currentUrl = this.removeCodeAndState(currentUrl);
				let urlLink = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appID +
					"&redirect_uri=" +
					encodeURIComponent(currentUrl) +
					"&response_type=code&scope=snsapi_userinfo&state=" + Date.now() + "#wechat_redirect";
				console.log('url链接', urlLink)
				window.location.href = urlLink
			},
			copyText(text) {
				if (navigator.clipboard) {
					navigator.clipboard.writeText(text).then(() => {
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						})
					}).catch(err => {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						})
						console.error('复制失败', err)
					})
				} else {
					// 兼容处理
					this.legacyCopy(text)
				}
			},
			legacyCopy(text) {
				const textarea = document.createElement('textarea')
				textarea.value = text
				textarea.readOnly = true
				textarea.style.position = 'absolute'
				textarea.style.left = '-9999px'
				document.body.appendChild(textarea)
				textarea.select()
				const result = document.execCommand('copy')
				document.body.removeChild(textarea)
				if (result) {
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				}
			},
			// 获取重定向联接中的code
			async getwxCode() {
				console.log("当前页面window.location", window.location);
				const code = this.getQueryParameter("code");
				const userInfo = localStorage.getItem("userInfo");
				if (userInfo) {
					this.isLoggedIn = true;
					return;
				}
				if (code) {
					let that = this
					console.log("请求后端获取用户信息");
					try {
						const tokenResponse = await $index.getAccessToken({
							code: code,
						});
						const accessToken = tokenResponse.data.accessToken;
						const userInfo = await $index.getUserInfo({
							accessToken: accessToken,
						});
						// 最终登录token
						const lastTokenInfo = await $index.getToken(userInfo.data);
						localStorage.setItem("userInfo", JSON.stringify(lastTokenInfo.data.login_user));
						localStorage.setItem(
							"tokenValue", lastTokenInfo.data.access_token);
						localStorage.setItem("isLoggedIn", true);
						this.isLoggedIn = true;
						this.userInfo = userInfo.data;
						this.userid = userInfo.data.openid;
						this.loginBtn = true;
						// uni.showModal({
						// 	content: '点击确定，会复制token的值',
						// 	success: res => {
						// 		if (res.confirm) {
						// 			that.copyText(lastTokenInfo.data.access_token)
						// 		}
						// 	},
						// });
						uni.showToast({
							title: "登录成功",
							icon: "success",
						});
						setTimeout(() => {
							let pagePrevPath = localStorage.getItem("pagePrevPath");
							console.log('跳转路径：', pagePrevPath)
							if (pagePrevPath) {
								localStorage.setItem("pagePrevPath", '');
								uni.navigateTo({
									url: pagePrevPath
								});
							} else {
								uni.switchTab({
									url: '/pages/index/index'
								});
							}
						}, 1500)
					} catch (error) {
						console.error("获取 access_token 失败:", error);
						throw error;
						uni.showToast({
							title: "登录出错",
							icon: "error",
							durtation: 3000,
						});
					}
				} else {
					this.isLoggedIn = false;
					// this.changeTab(0);
					localStorage.setItem("isLoggedIn", false);
					if (localStorage.getItem("special_index") == 4) {
						uni.showToast({
							title: "未授权",
							icon: "error",
							duration: 2000,
						});
					}
					console.log("没有code");
				}
				console.log("结束getwxcode函数");
			},
			removeCodeAndState(url) {
				// 正则匹配 code= 和 state= 的部分
				const regex = /code=[^&]*&state=[^&#]*\?{0,1}/;

				// 使用正则替换匹配的部分，并且处理可能的 `/?#` 变成 `/#`
				const cleanedUrl = url.replace(regex, "").replace("/?#", "/#");

				return cleanedUrl;
			},
			getQueryParameter(name) {
				const urlParams = new URLSearchParams(window.location.search);
				return urlParams.get(name);
			},
			getUserOpenid() {
				const userinfo = JSON.parse(localStorage.getItem("userInfo"));
				if (userinfo) {
					this.userid = userinfo.openid;
				}
			},
			//
			getFlow() {
				$index.getImage({
					show_position: 16,
					type: 0
				}).then(res => {
					this.Json = res;
					this.imageData = res.list;
				});
			},
		}
	};
</script>